package cn.yto.print.listener;

import cn.yto.print.utils.WeightUtil;
import com.fazecast.jSerialComm.SerialPort;
import com.fazecast.jSerialComm.SerialPortDataListener;
import com.fazecast.jSerialComm.SerialPortEvent;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;
import java.util.function.Consumer;


@Slf4j
public class SerialPorListener implements SerialPortDataListener {

    // 串口实例
    private final SerialPort attachedPort;
    private final Consumer<Double> dataHandler;

    public SerialPorListener(SerialPort port, Consumer<Double> onData) {
        this.attachedPort = Objects.requireNonNull(port, "SerialPort不能为空");
        this.dataHandler = Objects.requireNonNull(onData, "数据处理回调不能为空");
    }

    @Override
    public int getListeningEvents() {
        final int eventType = SerialPort.LISTENING_EVENT_DATA_AVAILABLE;
        return eventType;
    }

    @Override
    public void serialEvent(SerialPortEvent event) {
        if (!Objects.equals(event.getEventType(), SerialPort.LISTENING_EVENT_DATA_AVAILABLE)) {
            return;
        }
        int availableBytes = attachedPort.bytesAvailable();
        if (availableBytes <= 0) {
            return;
        }
        byte[] buffer = new byte[availableBytes];
        int actualReadBytes = attachedPort.readBytes(buffer, buffer.length);
        if (actualReadBytes <= 0) {
            return;
        }
        String rawData = new String(buffer, 0, actualReadBytes);
        try {
            double parsedWeight = WeightUtil.parseWeightData(rawData);
            dataHandler.accept(parsedWeight);
        } catch (Exception ex) {
            log.error("读取串口设备数据时出现异常", ex);
        }
    }

}

